import json

from pydantic import BaseModel

from ..crud.user_crud import get_user_by_name
from ..utils.file_tools import download_file
from fastapi import APIRouter, Depends, BackgroundTasks, Body,HTTPException
import os
from ..dependencies import oauth2_scheme
from ..utils.jwt_handler import get_username
from ..models.ai_models.vedio_api import run_coze_workflow as video_create_ai
from sqlalchemy.orm import Session
from ..database.db import get_db
from ..crud.video_crud import create_video as create_video_db, update_video_by_id
from typing import Optional
from ..utils.uploads_oss import main as upload_on_oss

videocreate=APIRouter(prefix="/video", tags=["视频"])

@videocreate.get("/")
async def get_auth(username: str = Depends(get_username)):
    return {
        "code":200,
        "message":"video",
        "data":{
            "username":username,
            "message":"video"
        }
        }

@videocreate.post("/createvideo")
async def video_create(demand: str = Body(..., description="视频需求"),
                       video_name: str = Body(..., description="视频名称"),
                       username: str = Depends(get_username),
                       db: Session = Depends(get_db)):

    user=get_user_by_name(db,username)
    from dotenv import load_dotenv
    # 加载 .env 文件中的环境变量
    load_dotenv()
    # 现在可以读取环境变量
    # WORKFLOW_ID = os.getenv("WORKFLOW_ID_VIDEO")
    WORKFLOW_ID="7528679746101182464"
    API_TOKEN ="pat_gF7zO0DniiE9heVum5i7YoNBA9QoApKNkLk6mXy5Zlha360QXxFLKz51zN0dcw4n"
    # VIDEO_DOWNLOAD_PATH = os.getenv("VIDEO_DOWNLOAD_PATH")
    SOURCES_PATH=os.getenv("SOURCES_PATH")
    result = video_create_ai(demand, workflow_id=WORKFLOW_ID, api_token=API_TOKEN)
    try:
        video_data = json.loads(result)
        video_url = video_data.get("output")
    except json.JSONDecodeError:
        video_url = None

    video_hou_url="sources/videos/download/"+f"{video_name}.mp4"
    video_all_name=f"{video_name}.mp4"
    video_item = create_video_db(db, video_all_name, video_hou_url)

    save_path = os.path.join(SOURCES_PATH,video_hou_url)
    if video_url:
        # video_item = create_video_db(db, video_name, video_url)
        download_file(video_url, save_path)
        upload_on_oss(key=video_hou_url,file_path=save_path)
        return {
            "code":200,
            "message": "Video downloaded",
            "path": video_url,
            "video_item":video_item
        }
    else:
        raise HTTPException(status_code=404, detail="Video URL not found")


class UpdateVideoParams(BaseModel):
    video_id: int
    video_name: str
    video_type: Optional[int] = 1
@videocreate.post("/update")
async def update_video(params: UpdateVideoParams, username: str = Depends(get_username), db: Session = Depends(get_db)):
    """

    - video_id: 视频id
    - video_name: 视频名
    - video_type: 视频类型，1 ai生成 2 用户上传
    """
    user=get_user_by_name(db,username)
    video_all_name=f"{params.video_name}.mp4"
    video_db=update_video_by_id(db, params.video_id, video_all_name, params.video_type)
    return {
        "code":200,
        "message":"更新成功",
        "data":video_db
    }
